import { downloadImages, getCanvasContext } from '@/utils/file'
import type { PDFDocumentProxy } from 'pdfjs-dist'
import type { RenderParameters } from 'pdfjs-dist/types/src/display/api'
import { ref, unref } from 'vue'

export const usePdf2Img = () => {
  const base64List = ref<string[]>([])

  // 解析pdf
  const parsePDF = async () => {}

  // 转换pdf
  const transferPDF2Img = async (pdf: PDFDocumentProxy) => {
    base64List.value = []
    const numPages = pdf.numPages
    for (let i = 1; i <= numPages; i++) {
      const page = await pdf.getPage(i)
      const viewport = page.getViewport({ scale: 1.0 })
      const { canvas, context } = getCanvasContext(viewport.width, viewport.height)
      const renderContext: RenderParameters = {
        canvasContext: context,
        viewport: viewport,
      }
      await page.render(renderContext).promise
      base64List.value.push(canvas.toDataURL('image/png', 1))
    }
  }

  // 保存图片
  const saveImg = (fileName: string, fileType: string) => {
    downloadImages(unref(base64List), fileName, fileType)
  }

  return {
    parsePDF,
    transferPDF2Img,
    saveImg,
  }
}
